<template>
  <div>
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="inline-block">
          <svg-icon
            :icon-class="'svg_tbfk'"
            class="w-30px h-30px align-middle"
          />
          <span
            v-if="bpmnStatus"
            style="font-size: 16px; margin: 0px 0px 0 6px; font-weight: 600"
            >{{ bpmnStatus }}</span
          >
          <span
            v-else
            style="font-size: 16px; margin: 0px 0px 0 6px; font-weight: 600"
            >{{
              router.currentRoute.value.query.flag == 'update'
                ? '编辑商机'
                : '新建商机'
            }}</span
          >
        </div>

        <!-- 内容 -->
        <div class="text-right">
          <slot></slot>
          <!-- <el-button
            v-if="isExamine && isCanStart"
            plain
            type="primary"
            @click="handleSubmit('examine')"
            >发起申请</el-button
          > -->
          <el-button
            v-show="!formDisabled"
            :loading="btnLoading"
            type="primary"
            @click="btnCheck('save')"
            >保存</el-button
          >
          <el-button plain type="primary" @click="handleReturn">返回</el-button>
        </div>
      </div>
    </FixedOperation>

    <div class="py-20px">
      <el-form
        ref="ruleFormRef"
        :disabled="formDisabled"
        :model="addForm"
        :rules="formRules"
        label-position="right"
      >
        <div>
          <TitleName
            class="title text-#000 ml-20px"
            icon="i-carbon-bookmark-filled"
            title="基本信息"
          ></TitleName>

          <el-row :gutter="grid" class="px-20" style="margin-top: 24px">
            <el-col :span="8">
              <el-form-item
                label="客户名称："
                label-width="110"
                prop="customerName"
              >
                <el-input
                  v-model="addForm.customerName"
                  :disabled="isDisabled"
                  clearable
                  placeholder="请选择客户名称"
                  style="width: 100%"
                >
                  <template #append
                    ><el-button
                      icon="Search"
                      @click="selectCustomerFn('customerId')"
                  /></template>
                </el-input>
                <!-- <el-select
                  :disabled="isDisabled"
                  style="width: 100%"
                  v-model.trim="addForm.customerName"
                  filterable
                  clearable
                  :filter-method="queryCustomer"
                  @change="changeCustomer"
                  placeholder="请输入客户名称"
                >
                  <el-option
                    v-for="item in parentOptions"
                    :key="item.id"
                    :label="item.customerName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="税号:"
                label-width="60"
                prop="customerTaxcode"
              >
                <el-input
                  v-model.trim="addForm.customerTaxcode"
                  :disabled="isDisabled"
                  clearable
                  maxlength="50"
                  placeholder="请输入税号"
                ></el-input>
              </el-form-item>
            </el-col>
            <!--            <el-col :span="6">-->
            <!--              <el-form-item-->
            <!--                label="联系人："-->
            <!--                label-width="110"-->
            <!--                prop="contactName"-->
            <!--              >-->
            <!--                <el-select-->
            <!--                  v-model.trim="addForm.contactName"-->
            <!--                  :disabled="isDisabled"-->
            <!--                  :filter-method="queryContacts"-->
            <!--                  clearable-->
            <!--                  filterable-->
            <!--                  placeholder="请输入联系人"-->
            <!--                  style="width: 100%"-->
            <!--                  @change="contactsChange"-->
            <!--                >-->
            <!--                  <el-option-->
            <!--                    v-for="item in contactsOptions"-->
            <!--                    :key="item.id"-->
            <!--                    :label="item.contactName"-->
            <!--                    :value="item.id"-->
            <!--                  >-->
            <!--                  </el-option>-->
            <!--                </el-select>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <!--            <el-col :span="6">-->
            <!--              <el-form-item-->
            <!--                label="联系电话："-->
            <!--                label-width="92"-->
            <!--                prop="contactPhone"-->
            <!--              >-->
            <!--                <el-input-->
            <!--                  v-model.trim="addForm.contactPhone"-->
            <!--                  clearable-->
            <!--                  maxlength="50"-->
            <!--                  placeholder="请输入联系电话"-->
            <!--                ></el-input>-->
            <!--              </el-form-item>-->
            <!--            </el-col>-->
            <el-col :span="8">
              <el-form-item label="职位：" label-width="60" prop="job">
                <el-input
                  v-model.trim="addForm.job"
                  clearable
                  maxlength="50"
                  placeholder="请输入职位"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item label="联系人：" label-width="110" prop="attnName">
                <el-input
                  v-model.trim="addForm.attnName"
                  clearable
                  maxlength="50"
                  placeholder="请输入联系人"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="联系电话："
                label-width="110"
                prop="attnPhone"
              >
                <el-input
                  v-model.trim="addForm.attnPhone"
                  clearable
                  maxlength="50"
                  placeholder="请输入联系电话"
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="gridCol">
              <el-form-item
                label="商机标题："
                label-width="110"
                prop="titleName"
              >
                <el-input
                  v-model.trim="addForm.titleName"
                  clearable
                  maxlength="50"
                  placeholder="请输入商机标题"
                ></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="gridCol">
              <el-form-item label="商机状态：" label-width="110" prop="status">
                <el-select
                  v-model="addForm.status"
                  clearable
                  placeholder="请选择商机状态"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in business_stage"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="gridCol">
              <el-form-item
                label="项目类型："
                label-width="110"
                prop="projectType"
              >
                <el-select
                  v-model="addForm.projectType"
                  clearable
                  placeholder="请选择项目类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in project_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="客户类型："
                label-width="110"
                prop="customerGenre"
              >
                <el-select
                  v-model="addForm.customerGenre"
                  class="w-full"
                  placeholder="客户类型"
                >
                  <el-option
                    v-for="(dict, index) in business_customer_type"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="客户行业："
                label-width="110"
                prop="customerIndustry"
              >
                <el-select
                  v-model="addForm.customerIndustry"
                  class="w-full"
                  placeholder="请选择客户行业"
                >
                  <el-option
                    v-for="(item, index) in industry_category"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="gridCol">
              <el-form-item
                label="商机来源："
                label-width="110"
                prop="resource"
              >
                <el-select
                  v-model="addForm.resource"
                  clearable
                  placeholder="请选择商机来源"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in business_source"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="推广分类："
                label-width="110"
                prop="popularizeTypeCode"
              >
                <el-select
                  v-model="addForm.popularizeTypeCode"
                  class="w-full"
                  placeholder="请选择推广分类"
                  @change="popularizeTypeFn"
                >
                  <el-option
                    v-for="(dict, index) in popularize_type"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item label="预计收益：" label-width="110" prop="revenue">
                <el-input
                  v-model.trim="addForm.revenue"
                  clearable
                  maxlength="50"
                  placeholder="请输入预计收益"
                >
                  <template v-slot:append>元</template>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="gridCol">
              <el-form-item
                label="赢单可能性："
                label-width="110"
                prop="percent"
              >
                <el-select
                  v-model="addForm.percent"
                  clearable
                  placeholder="请选择赢单可能性"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in winner_order_possibility"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="销售预期："
                label-width="110"
                prop="saleDate"
              >
                <el-date-picker
                  v-model="addForm.saleDate"
                  placeholder="请选择时间"
                  style="width: 100%"
                  type="date"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="gridCol">
              <el-form-item
                label="归属人员："
                label-width="110"
                prop="belongId"
              >
                <el-select
                  v-model="addForm.belongId"
                  class="w-full"
                  clearable
                  placeholder="请选择归属人员"
                  @focus="userInputFocus"
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['belongId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="gridCol">
              <el-form-item
                label="主管税务机关："
                label-width="120"
                prop="taxAuthorityId"
              >
                <el-tree-select
                  v-model="addForm.taxAuthorityId"
                  :check-strictly="true"
                  :data="taxTreeData"
                  :props="{
                    value: 'id',
                    label: 'label',
                    children: 'children'
                  }"
                  filterable
                  node-key="id"
                  placeholder="请输入主管税务机关"
                  style="width: 100%"
                  value-key="id"
                  @change="changeType"
                />
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row :gutter="grid" class="px-20">
            <el-col :span="24">
              <el-form-item
                label="项目关键需求："
                label-width="110"
                prop="projectDemand"
              >
                <el-input
                  v-model.trim="addForm.projectDemand"
                  :rows="4"
                  clearable
                  maxlength="300"
                  placeholder="请输入项目描述"
                  type="textarea"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <div class="add-product">
      <TitleName
        class="title text-#000 ml-20px"
        icon="i-carbon-bookmark-filled"
        title="产品"
      ></TitleName>

      <avue-crud
        ref="crudProduct"
        :data="addForm.productList"
        :disabled="formDisabled"
        :option="crudOptionProduct"
      >
        <template #menu-left>
          <el-button
            :disabled="formDisabled"
            icon="Plus"
            type="primary"
            @click="addProduct"
            >添加产品</el-button
          >
        </template>
        <template #menu="{ row, index }">
          <el-button
            :disabled="formDisabled"
            icon="Delete"
            link
            plain
            @click="delRowProduct(row, index)"
            >删除</el-button
          >
        </template>
        <template #empty>
          <div>暂无数据</div>
        </template>
        <template #footer>
          <el-col :span="24" class="py-2 text-right">
            产品记录数：<span class="text-blue-500"
              >{{ countCrudData.num }}条</span
            >
            产品总数：<span class="text-blue-500">{{
              countCrudData.total
            }}</span
            >个 产品总售价：<span class="text-blue-500"
              >{{ countCrudData.totalDiscountPrice }}元</span
            >
          </el-col>
          <!-- <el-button
            plain
            type="primary"
            icon="Plus"
            class="w-full"
            @click="addProduct"
            >添加产品</el-button
          > -->
        </template>
      </avue-crud>
    </div>
    <!-- 物料选择弹窗 -->
    <ProductDialog
      v-model="dialogData.open"
      :dialogData="dialogData"
      @getData="productDialogFn"
    />
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @close="closeFn"
      @ok="selectDialogData"
    ></SelectDialog>

    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
      @ok="selectCustomerData"
    ></SelectCustomer>

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @close="handleClose('examine')"
      @initiate="handleClose('initiate')"
    />
  </div>
</template>

<script name="addNiche" setup>
import {
  createCustomer, //创建客户
  getListByCustomerName, //企业客户列表
  getDetailTactlistByCactName
} from '@/api/customerManage/customerList'
import { getCustomerEditInfo } from '@/api/customerManage/customerList' //客户详情
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import { getCustomerInfo } from '@/api/customerManage/customerList'
import useUserStore from '@/store/modules/user'
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import { formRules } from '../module/formData'
import {
  business_stage,
  business_source,
  project_type,
  winner_order_possibility,
  industry_category,
  measurement_unit, //产品单位
  business_customer_type, //客户类型
  popularize_type,
  work_order_type //推过分类
} from '@/hooks/dict/business.js'

import useTagsViewStore from '@/store/modules/tagsView'
import { saveNiche, nicheDetail } from '@/api/nicheManage'
import { getContactInfo } from '@/api/customerManage/contactList'
import { getConfigKey } from '@/api/system/config'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'
// import { affixEmits } from 'element-plus'
const { proxy, type } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const btnLoading = ref(false) //按钮加载状态
//表单内的栅格化设置
const grid = ref(24)
const gridCol = ref(12)
const isDisabled = ref(false)
const userStore = useUserStore()
const props = defineProps({
  id: {
    type: String || Number
  }
})
const data = reactive({
  addForm: {
    titleName: null, //商机标题
    companyId: null,
    deptId: null,
    customerId: null, //客户Id
    customerName: null, //客户名称
    customerTaxcode: null, //税号
    contactId: null, //客户联系人id
    contactName: null, //客户联系人
    contactPhone: null, //联系电话
    status: '1', //商机状态
    resource: null, //商机来源
    projectType: null, //项目类型
    percent: null, //赢单可能性
    revenue: null, //预计收益
    belongId: null, //归属人员
    projectDemand: null, //项目需求
    saleDate: null, //销售日期
    productList: [], //产品
    customerType: 'customer', //客户选择下拉
    taxAuthorityId: null, //主管税务机关id
    taxAuthorityName: null, //主管税务机关名称
    customerGenre: null, //客户类型
    customerIndustry: null, //客户行业
    job: null, //职务
    popularizeTypeCode: null, //推广分类代码
    popularizeTypeName: null, //推广分类名称
    attnName: null, //联系人
    attnPhone: null //联系电话
  },
  parentOptions: [], //客户列表
  loadingSelect: false,
  selectOptionObj: {}, // select
  dialogParam: {},
  dialogData: {
    open: false
  },
  countCrudData: {},
  businessType: userStore.userInfo.businessSector
    ? userStore.userInfo.businessSector.split(',')
    : [], //人员所属业务板块信息、businessSector
  crudOptionProduct: {
    header: true,
    menu: true,
    delBtn: false,
    editBtn: false,
    addBtn: false,
    addRowBtn: false,
    saveBtn: false,
    cancelBtn: false,
    cellBtn: false,
    // searchBtn: false,
    refreshBtn: false,
    columnBtn: false,
    menuWidth: 100,
    column: [
      {
        label: '产品名称',
        prop: 'name',
        cell: false,
        rules: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '产品编号',
        prop: 'number',
        cell: false
      },
      {
        label: '规格型号',
        prop: 'specification',
        cell: false
      },
      {
        label: '单位',
        prop: 'unit',
        type: 'select',
        dicData: measurement_unit,
        cell: false
      },
      {
        label: '标准单价',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入标准单价',
            trigger: 'blur'
          }
        ],
        cell: false
      },
      {
        label: '数量',
        prop: 'num',
        type: 'number',
        min: 0,
        class: 'w-full',
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }
        ],
        cell: true
      },

      {
        label: '备注',
        prop: 'remark',
        // type: 'textarea',
        // maxRows: 1,
        rules: [
          {
            required: false,
            message: '请输入备注',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },
  dialogParamA: {}, //客户弹窗
  customerOption: {} //客户选择下拉
})

// 销售人员 label
const saler = ref()
const {
  addForm,
  parentOptions,
  loadingSelect,
  selectOptionObj,
  dialogParam,
  crudOptionProduct,
  dialogData,
  countCrudData,
  businessType,
  dialogParamA,
  customerOption
} = toRefs(data)
const businessId = ref(null)

const examineParam = ref({}) // 传递的参数
const isExamine = ref(true) // 判断是否走审批按钮
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情
const bpmnStatus = ref('') //表单标题
const formDisabled = ref(false) // 禁用表单

watch(
  [() => props.id, () => route.query.type],
  async val => {
    if (props.id && route.name == 'EditNiche') {
      //编辑
      businessId.value = props.id
      await getBusinessDetail() //查询详情接口

      // //根据业务查询审批状态
      // await getBusinessProStatusFn()
      // // 判断表单是否可编辑  获取当前流程节点
      // let res = await getNodeData(props.id)
      // bpmnStatus.value = res.data?.nowTaskName
      // formDisabled.value =
      //   res.data == null || res.data?.isFirst == 'Y' ? false : true
    } else if (props.id && route.name == 'WorkDetail') {
      businessId.value = props.id
      await getBusinessDetail()
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        formDisabled.value =
          res.data == null || res.data?.isFirst == 'Y' ? false : true
      }
      // formDisabled.value = route.query.processed == 'true' ? false : true
      isCanStart.value = false
    } else if (route.query.type == 'customer') {
      //企业客户
      addForm.value.customerId = route.query.customerId
      addForm.value.customerName = route.query.customerName
      //   addForm.value.projectType = route.query.projectType
      await queryCustomer(route.query.customerName)
      await changeCustomer(addForm.value.customerId)
      isDisabled.value = true
    } else if (route.query.type == 'contacts') {
      //联系人
      addForm.value.contactName = route.query.contactsName
      //   addForm.value.projectType = route.query.projectType
      await queryContacts(
        route.query.contactsName,
        route.query.contactsId,
        route.query.type
      )
      await contactsChange(route.query.contactsId)
      await getContactInfoList(route.query.contactsId)
      addForm.value.customerId = route.query.contactsId
      addForm.value.customerName = route.query.contactsName
      addForm.value.contactId = route.query.contactsId
      //   parentOptions.value = [ { id: route.query.contactsId, customerName: route.query.contactsName }]
      isDisabled.value = true
    } else {
      isDisabled.value = false
      isExamine.value = true
      // 不走业务流程
      // initFlowFn('31')
    }
  },
  {
    immediate: true
  }
)
onMounted(() => {
  // 计算产品数据
  countCrudData.value = computed(() => {
    let obj = {
      num: 0,
      total: 0,
      totalDiscountPrice: 0
    }
    if (addForm.value.productList && addForm.value.productList.length > 0) {
      addForm.value.productList.forEach(item => {
        obj.total = Number(item.num) + Number(obj.total) // 产品总数
        obj.totalDiscountPrice =
          Number(item.price) * Number(item.num) + Number(obj.totalDiscountPrice) //产品总售价
        //产品总数：countCrudData.total
        //产品总金额：countCrudData.totalDiscountPrice
        //产品总金额： countCrudData.totalPrice
      })
      obj.num = addForm.value.productList.length // 产品数量
    }
    return obj
  })
})
//联系人详情--身份证号
function getContactInfoList(id) {
  getContactInfo(id).then(res => {
    addForm.value.customerTaxcode = res.data.co.idNumber
      ? res.data.co.idNumber
      : ''
  })
}
//获取详情
async function getBusinessDetail() {
  const response = await nicheDetail(businessId.value)
  response.data.productList.forEach((e, i) => {
    if (e.id) {
      response.data.productList[i].$cellEdit = true
    }
  })
  addForm.value = { ...response.data }
  //   queryCustomer(response.data.customerName)
  addForm.value.belongId = 'U' + response.data.belongId
  selectOptionObj.value['belongId'] = [
    {
      label: response.data.belongName,
      uuid: 'U' + response.data.belongId,
      id: response.data.belongId
    }
  ]
  // getDefaultUserInfo(response.data.belongId)
  //转换主管税务机关
  if (response.data.taxAuthorityId != null) {
    addForm.value.taxAuthorityId = parseInt(addForm.value.taxAuthorityId)
  }
}
/***客户联系人数据  start*/
const contactsOptions = ref([])

//联系人
async function queryContacts(val, contactsId, type) {
  console.log('联系人', val, type)
  if (type) {
    loadingSelect.value = true
    let params = {
      pageSize: 10,
      entId: '',
      contactName: val || '',
      ids: contactsId || ''
    }
    let res = await getDetailTactlistByCactName(params)
    contactsOptions.value = res.data
    loadingSelect.value = false
  } else if (addForm.value.customerId) {
    loadingSelect.value = true
    let params = {
      pageSize: 10,
      entId: addForm.value.customerId,
      contactName: val || ''
    }
    let res = await getDetailTactlistByCactName(params)
    contactsOptions.value = res.data
    loadingSelect.value = false
  } else if (val) {
    addForm.value.contactName = val
  }
}
// 客户联系人选中事件
const contactsChange = val => {
  console.log('select', val)
  let newData = JSON.parse(JSON.stringify(contactsOptions.value))
  let obj = newData.filter(item => {
    return item.id == val
  })
  addForm.value.contactName = obj.length == 0 ? '' : obj[0].contactName
  addForm.value.contactPhone = obj.length == 0 ? '' : obj[0].contactNumber
}
//客户列表
async function queryCustomer(val) {
  if (!val) {
    return
  }
  let params = {
    pageSize: 10,
    customer: val
  }
  let comRes = await getListByCustomerName(params)
  parentOptions.value = comRes.data
  if (parentOptions.value.length == 0) {
    contactsOptions.value = []
    addForm.value.customerId = ''
    addForm.value.customerName = val
    addForm.value.contactId = ''
    addForm.value.contactName = ''
    addForm.value.contactPhone = ''
    addForm.value.customerTaxcode = ''
  }
}
//重置
function resetQuery() {
  addForm.value = {
    companyId: null, //登录人id
    deptId: null, //登录人id
    customerId: null, //客户Id
    customerName: null, //客户名称
    customerTaxcode: null, //税号
    contactId: null, //客户联系人id
    contactName: null, //客户联系人
    contactPhone: null, //联系电话
    status: null, //商机状态
    resource: null, // 商机来源
    projectType: null, //项目类型
    percent: null, //赢单可能性
    revenue: null, //预计收益
    belongId: null, //归属人员ID
    projectDemand: null, //项目需求
    saleDate: null, //销售日期
    productList: [] //产品
  }
}
// 编辑商机校验
const btnCheck = async val => {
  let res = await getConfigKey('small_medium_password')
  proxy
    .$prompt('输入验证码开启此功能', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: false,
      inputType: 'password',
      closeOnClickModal: false
      // inputPattern: /^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{8,16}$/,
      // inputErrorMessage: '请输入长度为8-16大小写字母及数字，特殊字符'
    })
    .then(({ value }) => {
      if (value !== res.msg) return proxy.$modal.msgError('密码错误')
      if (val == 'save') {
        handleSubmit(val)
      }
    })
    .catch(() => {})
}
//保存
function handleSubmit(type) {
  return new Promise((resolve, reject) => {
    proxy.$refs['ruleFormRef'].validate(async valid => {
      if (valid) {
        if (addForm.value.customerId) {
          await saveForm(type)
          resolve('保存成功')
        } else {
          let data = {
            bizCustomerAddDto: {
              origin: '9', //客户来源 (默认）
              customerType: '3', //客户类型 (默认）
              starRating: 0, //客户星级 (默认）
              orgId: userStore.user.orgId, //登录人的orgid (自取)
              userId: userStore.user.userId, //登录人userid （自取）
              customerName: addForm.value.customerName, //客户名称 （表单）
              mainContactName: addForm.value.contactName, //首要联系人姓名 （表单）
              mainContactPhone: addForm.value.contactPhone, //首要联系人手机 （表单）
              deptId: userStore.user.deptId, //登录人deptId （自取）
              userName: userStore.user.userName, //登录人姓名 （表单）
              customerTaxcode: addForm.value.customerTaxcode //客户税号
            },
            bizCustomerExtDto: {},
            bizContactDto: {
              sex: '2', //联系人性别 (默认）
              orgId: userStore.user.orgId, //登录人的orgid （自取）
              userId: userStore.user.userId, //登录人userid（自取）
              deptId: 63005, //登录人deptId（自取）
              userName: userStore.user.userName, //登录人姓名 （自取）
              entType: '1', //企业类型 (默认）
              isChiefly: '1' // (默认）
            },
            bizCustomerInvinfoDto: {
              invoiceType: '1', //发票类型 (默认）
              headerType: '1', //发票抬头 (默认）
              invContentType: '1' //发票内容 (默认）
            },
            bizContactExtDto: {}
          }
          console.log('添加新客户', data)
          createCustomer(data).then(res => {
            addForm.value.customerId = res.data
            if (
              addForm.value.contactId == null ||
              addForm.value.contactId == ''
            ) {
              getCustomerInfo(addForm.value.customerId).then(res => {
                addForm.value.contactId = res.data.vo.id
                saveForm()
              })
            }
          })
        }
      } else {
        reject('验证失败')
      }
    })
  })
}

//保存
async function saveForm(type) {
  btnLoading.value = true
  let data = JSON.parse(JSON.stringify(addForm.value))
  if (addForm.value.belongId) {
    // 获取查询到的user数据对象
    let userObj = getUniqueUserId(
      selectOptionObj.value['belongId'],
      addForm.value.belongId
    )
    console.log('userObj', userObj)
    //获取userid
    data.belongId = userObj.id
  }

  for (let i = 0; i < data.productList.length; i++) {
    delete data.productList[i].id
  }
  try {
    let res = await saveNiche(data)
    if (res.code == 200) {
      btnLoading.value = false
      // 审批流程id赋值
      examineParam.value.businessId = res.data
      businessId.value = res.data.id
      await getBusinessDetail()
      if (type == 'examine') {
        handleExamine()
      } else if (type == 'save') {
        proxy.$modal.msgSuccess('保存成功!')
        proxy.useReturn(
          '',
          () => {
            //返回上一步
            handleReturn()
          },
          async () => {
            //继续
          }
        )
      }
    }
  } catch (error) {
    btnLoading.value = false
  }
}

// 删除行
function delRowProduct(row, index, done) {
  proxy
    .$confirm('是否删除该产品', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      addForm.value.productList.splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}

// 添加产品
function addProduct() {
  console.log('addProduct===>', businessType.value)
  dialogData.value.open = true
  dialogData.value.productQuery = {
    productFilter: 'y', //过滤所属板地
    businessType: businessType.value //所属板
  }
}
// 确定添加产品
function productDialogFn(val, tabName) {
  switch (tabName) {
    case 'ProductMange':
      val.forEach(e => {
        addForm.value.productList.push({
          ...e,
          ...{
            $cellEdit: true,
            num: 1
          }
        })
      })
      break
    case 'ComboMange':
      val.forEach(e => {
        e.productInfoList.forEach(item => {
          addForm.value.productList.push({
            ...item,
            ...{
              $cellEdit: true
            }
          })
        })
      })
      break
  }
}

/**** 归属人员 模块 start */
/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId) {
  console.log('userId', userId)
  console.log('user', userStore.user)
  let id = ''
  if (userId) {
    id = userId
  } else {
    //获取当前用户id
    // id = userStore.user.userId
  }
  //获取人员数据
  const deptUserData = await commonStore.getUseTreeData()
  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
  selectOptionObj.value.belongId = obj
  addForm.value.belongId = obj && obj.length > 0 ? obj[0].uuid : ''
}

/**
 * 项目负责人获取焦点事件
 */
function userInputFocus() {
  dialogParam.value = {
    type: 'belongId',
    title: '请选择人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    apiParams: {
      disabled: 'false',
      deptId:
        useUserStore().user['orgId'] == '484'
          ? undefined
          : useUserStore().user['orgId']
    },
    checkStrictly: false
  }
  dialogParam.value.isDialog = true
  dialogParam.value.defaultCheckedKeys = [addForm.value.belongId] || []
}
/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'belongId':
      selectOptionObj.value['belongId'] = val.selectData
      addForm.value.belongName = val.labelData.toString()
      addForm.value.belongId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : ''
      break
  }
}
/**
 * 弹出框关闭
 * @param {*} val
 */
const closeFn = val => {
  dialogParam.value.isDialog = false
}

/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = addForm.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = addForm.value[keyName]
      dialogParamA.value.defaultCheckedLabel = addForm.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      console.log('客户名称', val)
      customerOption.value.customerId = val.selectData
      addForm.value.customerType = val.tabVal
      addForm.value.customerName = val.labelData.toString()
      addForm.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      if (addForm.value.customerId) {
        selectCustomerItem()
      }
      break
  }
}
async function selectCustomerItem() {
  switch (addForm.value.customerType) {
    case 'customer':
      console.log('企业')
      changeCustomer(addForm.value.customerId)
      break
    case 'cusLink':
      console.log('个人')
      addForm.value.contactId = addForm.value.customerId
      addForm.value.contactName = addForm.value.customerName
      await queryContacts(addForm.value.contactName, '', 'contacts')
      await contactsChange(addForm.value.contactId)
      await getContactInfoList(addForm.value.contactId) //个人用户详情
      break
  }
}
// 改变客户名称后客户联系人 联系电话清空
async function changeCustomer(val) {
  // //获取客户联系人
  await getCustomerEditInfo(val).then(res => {
    let resData = res.data
    //联系人赋值
    if (resData.bizCustomerAddDto.mainContactId) {
      addForm.value.contactId = resData.bizCustomerAddDto.mainContactId
      addForm.value.contactName = resData.bizCustomerAddDto.mainContactName
      queryContacts()
    }
    //联系电话赋值
    if (resData.bizCustomerAddDto.mainContactPhone) {
      addForm.value.contactPhone = resData.bizCustomerAddDto.mainContactPhone
    }
    // 客户社会信用代码/身份证赋值
    if (resData.bizCustomerAddDto.customerTaxcode) {
      addForm.value.customerTaxcode = resData.bizCustomerAddDto.customerTaxcode
    }
  })
}

/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
 发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13 销售14 通知公告 27
/**
 * 提交审批 按钮
 */
const handleExamine = async () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = addForm.value.titleName //标题
  examineParam.value.isfgs = useUserStore().user['orgId'] == '484' ? 0 : 1 //是否省公司
  examineParam.value.categoryCode = '31' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: addForm.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('31')
  } else {
    isCanStart.value = false
  }
  // if (statusRes.data.status) {
  //   // status判断流程环节05表示结束
  //   isCanStart.value = true
  // } else {
  //   isCanStart.value = false
  // }
}
/***************************业务流程 模块 end****************************************************************/

function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}

// 流程同意调用的方法
async function handleSave() {
  if (!formDisabled.value) {
    return await handleSubmit()
  }
}

//暴露出保存方法
defineExpose({ handleSave })

async function init() {
  addForm.value.deptId = userStore.user.deptId
  addForm.value.companyId = userStore.user.orgId
  await getDefaultUserInfo(userStore.user.userId)
  // 获取主管税务机关下拉数据
  commonStore.getTaxTreeData().then(data => {
    taxTreeData.value = data
  })
}
init()
/****商机 模块 字段增加 2024/6/24 gbq*****/
// 主管税务机关 获取名称
function changeType(val) {
  let obj = getTreeNodeByParam(toRaw(taxTreeData.value), val, 'id', [])
  addForm.value.taxAuthorityName = obj && obj.length > 0 ? obj[0].label : ''
}
// 推广分类 选中
const popularizeTypeFn = val => {
  const popularizeType = JSON.parse(
    JSON.stringify(toRaw(popularize_type.value))
  )
  console.log(val, toRaw(popularize_type), popularize_type.value, '111111')
  const obj = popularizeType.find(v => v.value == val)
  addForm.value.popularizeTypeName = obj ? obj.label : ''
}
const taxTreeData = ref([]) //主管税务机关
/****商机 模块 字段增加 2024/6/24 gbq end*****/
</script>

<style lang="scss" scoped>
:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
